// pages/user/user-withdraw/index.js
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    CustomBar: app.globalData.CustomBar,
    theme: app.globalData.theme, //全局颜色变量
    providerInfo: {},
    cardId: null,
    loading: false,
    withdrawAmount: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    app.initPage()
      .then(res => {
        this.loadProviderInfo()
      })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  // 获取当前师傅信息
  loadProviderInfo() {
    app.api.providerInfoGet().then(res => {
      let data = res.data || {}
      this.setData({
        providerInfo: data,
        cardId: data.cardId ? data.cardId.substring(data.cardId.length - 6) : '',
        withdrawAmount: data.accountBalance
      })
    })
  },
  withdrawAmountInputValue(e) {
    this.setData({
      withdrawAmount: e.detail.value
    })
  },
  // 提交申请
  subClick() {
    const that = this
    let withdrawAmount = this.data.withdrawAmount
    let accountBalance = this.data.providerInfo.accountBalance
    if (withdrawAmount <= 0) {
      wx.showToast({
        title: "请输入大于0的金额",
        icon: "none",
        duration: 2000
      });
      return
    }
    if (withdrawAmount > accountBalance) {
      wx.showToast({
        title: "最大可提现金额为" + accountBalance + "元",
        icon: "none",
        duration: 2000
      });
      return
    }
    wx.showModal({
      content: '是否确认提现？',
      cancelText: '我再想想',
      confirmColor: '#ff0000',
      success(res) {
        if (res.confirm) {
          that.setData({
            loading: true
          })
          app.api.providerWithdrawApply({
            withdrawAmount: withdrawAmount
          }).then(res => {
            that.setData({
              loading: false
            })
            wx.showToast({
              title: '申请成功，请等待审核',
              icon: 'success',
              duration: 2000,
              success: function () {
                setTimeout(function () {
                  wx.navigateBack({
                    delta: 1
                  });
                }, 1000)
              }
            })
          }).catch(() => {
            that.setData({
              loading: false
            })
          })
        }
      }
    })
  }
})